<template>
  <div class="search-page container">
    <!-- 搜索标题 -->
    <h2 class="search-title">
      搜索结果：
      <span class="keyword">"{{ route.query.q }}"</span>
    </h2>

    <!-- 加载中 -->
    <div v-if="loading" class="loading">正在搜索中...</div>

    <!-- 无结果 -->
    <div v-else-if="results.length === 0" class="no-result">
      没有找到与 <strong>{{ route.query.q }}</strong> 相关的内容 😢
    </div>

    <!-- 搜索结果列表 -->
    <div v-else class="post-list">
      <div
        v-for="post in results"
        :key="post.id"
        class="post-card"
        @click="goToPost(post.id)"
      >
        <div class="post-header">
          <h3 class="post-title">{{ post.title }}</h3>
          <div class="post-meta">
            <img
              v-if="post.avatar"
              :src="post.avatar"
              alt="avatar"
              class="avatar"
            />
            <span class="author">{{ post.nickname || post.username }}</span>
            <span class="time">{{ formatDate(post.createTime) }}</span>
          </div>
        </div>
        <p class="post-content">{{ getSummary(post.content) }}</p>
        <div class="post-tags">
          <el-tag
            v-for="(tag, index) in parseTags(post.tags)"
            :key="index"
            size="small"
            type="info"
          >
            {{ tag }}
          </el-tag>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import request from '../../utils/request'
import { ElTag } from 'element-plus'

const route = useRoute()
const router = useRouter()
const results = ref<any[]>([])
const loading = ref(false)

// 格式化时间
const formatDate = (time: string) => {
  return new Date(time).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 截取内容摘要
const getSummary = (content: string) => {
  return content.length > 100 ? content.slice(0, 100) + '...' : content
}

// 解析标签
const parseTags = (tags: string | null) => {
  if (!tags) return []
  return tags.split(',').map(t => t.trim()).filter(Boolean)
}

// 跳转文章详情页
const goToPost = (id: number) => {
  router.push(`/article/${id}`)
}

// 搜索函数
const fetchSearch = async (keyword: string) => {
  if (!keyword) return
  loading.value = true
  try {
    const res = await request.get('/api/posts/search', { params: { keyword } })
    console.log('请求+++++:', res)
    results.value = res.data || []
  } catch (err) {
    console.error('搜索失败:', err)
  } finally {
    loading.value = false
  }
}

// 页面加载时执行搜索
onMounted(() => {
  fetchSearch(route.query.q as string)
})

// 监听路由变化（支持连续搜索）
watch(
  () => route.query.q,
  (newQ) => {
    fetchSearch(newQ as string)
  }
)
</script>

<style scoped>
.search-page {
  padding: 40px 0;
}

.search-title {
  font-size: 24px;
  margin-bottom: 20px;
  font-weight: bold;
}

.keyword {
  color: #fc5531;
}

.loading {
  text-align: center;
  color: #888;
  font-size: 16px;
}

.no-result {
  text-align: center;
  color: #666;
  font-size: 18px;
  margin-top: 50px;
}

.post-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.post-card {
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

.post-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.12);
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.post-title {
  font-size: 20px;
  color: #333;
  font-weight: 600;
  margin-bottom: 8px;
}

.post-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #888;
  font-size: 14px;
}

.avatar {
  width: 26px;
  height: 26px;
  border-radius: 50%;
  object-fit: cover;
}

.post-content {
  color: #666;
  margin: 10px 0;
  line-height: 1.6;
}

.post-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 10px;
}
</style>
